package com.power.sifa.correction.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.ding.api.Di_userFeign;
import com.ding.dto.Di_deptDto;
import com.ding.dto.Di_messageDto;
import com.ding.dto.Di_todoDto;
import com.ding.dto.Di_userDto;
import com.ding.model.enumeration.St_pStatus;
import com.ding.service.Di_todoRemoteService;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.domain.YesNo;
import com.plf.common.utils.StringUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.model.Ha_depart;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.base.service.Ha_departService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.dao.Crc_group_personDao;
import com.power.sifa.correction.dao.Crc_personDao;
import com.power.sifa.correction.model.Crc_group_person;
import com.power.sifa.correction.model.Crc_person;
import com.power.sifa.correction.model.Cre_warning;
import com.power.sifa.correction.model.Cre_work_record;
import com.power.sifa.correction.model.enumeration.Tp_crc_warn;
import com.power.sifa.correction.model.pageInfo.Crc_personPageInfo;
import com.power.sifa.correction.model.pojo.bo.Crc_departBO;
import com.power.sifa.correction.service.Crc_personService;
import com.power.sifa.correction.service.Cre_warningService;
import com.power.sifa.correction.service.Cre_work_recordService;
import com.power.sifa.statistics.model.vo.MonitoringVO;
import com.power.sifa.util.service.impl.DidiSmsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 社区矫正人员信息业务层实现
 */
@Slf4j
@Service
public class Crc_personServiceImpl extends BaseServiceImpl implements Crc_personService {

    @Resource
    private Crc_personDao dao;
    @Resource
    private Crc_group_personDao crc_group_personDao;
    @Resource
    private Ha_departService ha_departService;
    @Resource
    private Ha_attachmentService ha_attachmentService;
    @Resource
    private Di_userFeign di_userFeign;
    @Resource
    private Cre_work_recordService cre_work_recordService;
    @Resource
    private Di_todoRemoteService di_todoRemoteService;
    @Resource
    private Cre_warningService cre_warningService;
    @Resource
    private SMService smService;

    @Override
    public Integer getNextval() {
        return dao.getNextval();
    }

    @Override
    public Crc_person getById(Serializable id) {
        Crc_person person = dao.findById(id).orElse(null);
        if (ObjectUtil.isNotNull(person)) {
            List<Crc_person> personList = Collections.singletonList(person);
            initSetDepartName(personList);
            queryAvatarUrl(personList);
            return personList.get(0);
        }
        return person;
    }

    @Override
    public Crc_person findPersonById(String id) {
        return dao.findPersonById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Crc_person crc_person) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (crc_person.getPrimaryKey() != null) {
            Crc_person crc_personfDb = dao.findById(crc_person.getPrimaryKey()).orElse(null);
            if (crc_personfDb != null) {
                BeanUtils.copyProperties(crc_person, crc_personfDb);
                crc_personfDb.setDeleted(0);
                dao.save(crc_personfDb);
                return;
            }
        }

        /*try {
            crc_person.setPhone(smService.decrypt(crc_person.getPhone()));
            crc_person.setName(smService.decrypt(crc_person.getName()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解密失败: name【{}】,phone【{}】");
        }*/
        if (!StringUtils.hasText(crc_person.getId())) {
            String id = String.format("%04d", dao.getNextval());
            crc_person.setId(id);
        }
        crc_person.setDeleted(0);
        if (!StringUtils.hasText(crc_person.getAdid())) {
            Ha_depart depart = queryDepartInfo(crc_person);
            if (ObjectUtil.isNotNull(depart)) {
                crc_person.setAdid(depart.getAdid());
            }
        }
        dao.save(crc_person);
    }

    @Override
    public void removeById(Serializable id) {
        List<String> ids = new ArrayList<>();
        ids.add((String) id);
        dao.removeByIds(ids);
    }

    @Override
    public Page<Crc_person> findAll(Crc_personPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        // 默认查询删除标志为0的数据
        pageInfo.setF_deleted(0);
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        Page<Crc_person> result = dao.findAll(spec, pageable);
        initSetDepartName(result.getContent());
        for (Crc_person person : result) {
            try {
                person.setPhone(smService.encrypt(person.getPhone()));
                person.setName(smService.encrypt(person.getName()));
                person.setCardno(smService.encrypt(person.getCardno()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Crc_person> findAll() {
        // 默认查询删除标志为0的数据
        Specification<Crc_person> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("deleted"), 0)
        ).getRestriction();
        List<Crc_person> result = dao.findAll(specification);
        initSetDepartName(result);
        return result;
    }

    @Override
    public void saveAll(List<Crc_person> list) {
        list.stream().forEach(element -> {
            element.setDeleted(0);
        });
        dao.saveAll(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveOrUpdate(List<Crc_person> list) {
        // 按照身份证进行过滤
        List<Crc_person> filterPerson = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Crc_person::getCardno))), ArrayList::new));
        if (CollectionUtil.isNotEmpty(filterPerson)) {
            // 查询当前在数据库的身份证号
            List<String> cardNo = filterPerson.stream().map(Crc_person::getCardno).collect(Collectors.toList());
            List<Crc_person> personList = dao.findByCardNos(cardNo);
            Set<String> cardNoSet = new HashSet<>();
            if (CollectionUtil.isNotEmpty(personList)) {
                personList.stream().forEach(element -> {
                    cardNoSet.add(element.getCardno());
                });
            }
            filterPerson.stream().forEach(element -> {
                if (cardNoSet.contains(element.getCardno())) {
                    Crc_person crc_personfDb = dao.findByCardNo(element.getCardno());
                    String oldId = crc_personfDb.getId();
                    if (crc_personfDb != null) {
                        BeanUtils.copyProperties(element, crc_personfDb);
                        crc_personfDb.setId(oldId);
                        crc_personfDb.setDeleted(0);
                        dao.save(crc_personfDb);
                    }
                } else {
                    element.setDeleted(0);
                    dao.save(element);
                }
            });
        }
    }


    @Override
    public PageDataResponse pageQuery(Crc_personPageInfo pageInfo) {
        List<Crc_person> personList = this.dao.pageQuery(pageInfo);
        initSetDepartName(personList);
        // 查询头像图片地址
        queryAvatarUrl(personList);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(personList)) {
            for (Crc_person personInfo : personList) {
                personInfo.geneText();
                try {
                    personInfo.setPhone(smService.encrypt(personInfo.getPhone()));
                    personInfo.setName(smService.encrypt(personInfo.getName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(personList);
        return page;
    }

    /**
     * 条件查询全部社矫人员数据
     *
     * @param pageInfo
     * @return
     */
    @Override
    public List<Crc_person> queryAllList(Crc_personPageInfo pageInfo) {
        List<Crc_person> personList = this.dao.listQuery(pageInfo);
        if (CollectionUtil.isNotEmpty(personList)) {
            try {
                for (Crc_person data : personList) {
                    data.setCardno(smService.decrypt(data.getCardno()));
                    data.setName(smService.decrypt(data.getName()));
                    data.setPhone(smService.decrypt(data.getPhone()));
                    data.geneText();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("身份证解密失败");
            }
        }
        initSetDepartName(personList);
        queryAvatarUrl(personList);
        return personList;
    }

    @Override
    public Crc_person findByCardNos(String cardno) {
        Crc_person person = dao.findByCardNo(cardno);
        initSetDepartName(Collections.singletonList(person));
        queryAvatarUrl(Collections.singletonList(person));
        return person;
    }

    @Override
    public List<Crc_person> findByPersonIds(List<String> personIds) {
        List<Crc_person> result = dao.findByPersonIds(personIds);
        initSetDepartName(result);
        queryAvatarUrl(result);
        return result;
    }

    @Override
    public Map<String, List<Crc_person>> findPersonByGroupIds(List<String> groupIds) {
        Map<String, List<Crc_person>> result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(groupIds)) {
            List<Crc_group_person> group_personList = this.crc_group_personDao.findByGroupIds(groupIds);
            if (CollectionUtil.isNotEmpty(group_personList)) {
                List<String> personIds = group_personList.stream().map(Crc_group_person::getPerid).distinct().collect(Collectors.toList());
                List<Crc_person> personList = this.findByPersonIds(personIds);
                initSetDepartName(personList);
                // 构建返回的map
                Map<String, List<Crc_group_person>> group_personMapList = group_personList.stream().collect(Collectors.groupingBy(Crc_group_person::getGrpid));
                for (String groupId : group_personMapList.keySet()) {
                    List<Crc_group_person> innerGroup = group_personMapList.get(groupId);
                    List<String> personIdList = innerGroup.stream().map(Crc_group_person::getPerid).distinct().collect(Collectors.toList());
                    List<Crc_person> innerPersonList = personList.stream().filter(element -> CollectionUtil.isNotEmpty(personIdList) && personIdList.contains(element.getId())).collect(Collectors.toList());
                    result.put(groupId, innerPersonList);
                }
            }
        }
        return result;
    }

    /**
     * 查询当前人员数据的司法所id
     *
     * @param crc_persons
     */
    private void initSetDepartName(List<Crc_person> crc_persons) {
        List<Ha_depart> departs = ha_departService.findAll();
        if (CollectionUtil.isNotEmpty(crc_persons) && CollectionUtil.isNotEmpty(departs)) {
            crc_persons.stream().forEach(el -> {
                if (ObjectUtil.isNotNull(el) && ObjectUtil.isNotNull(el.getDeptid())) {
                    Ha_depart depart = departs.stream().filter(item -> item.getId().equals(el.getDeptid())).findFirst().orElse(null);
                    if (ObjectUtil.isNotNull(depart)) {
                        el.setDeptname(depart.getName());
                    }
                }
            });
        }
    }

    /**
     * 查询头像图片的url地址
     *
     * @param personList
     */
    private void queryAvatarUrl(List<Crc_person> personList) {
        if (CollectionUtil.isNotEmpty(personList)) {
            // 拿取对应的id
            List<String> attachmentIds = personList.stream().filter(element -> ObjectUtil.isNotNull(element) && ObjectUtil.isNotNull(element.getAvatar())).map(Crc_person::getAvatar).collect(Collectors.toList());
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attachmentIds);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                personList.stream().forEach(m -> {
                    Optional.ofNullable(ha_attachmentMap.get(m.getAvatar())).ifPresent(then -> {
                        m.setAvatarUrl(ha_attachmentMap.get(m.getAvatar()).getPath());
                    });
                });
            }
        }
    }


    /**
     * 查询对应的id的司法所信息
     *
     * @param crc_persons
     * @return
     */
    private Ha_depart queryDepartInfo(Crc_person crc_persons) {
        if (ObjectUtil.isNotNull(crc_persons) && ObjectUtil.isNotNull(crc_persons.getDeptid())) {
            // 查询对应的司法所信息
            Ha_depart depart = ha_departService.getById(crc_persons.getDeptid());
            return depart;
        }
        return null;
    }

    /**
     * 查询全部的司法所信息
     *
     * @return
     */
    @Override
    public List<Ha_depart> findAllLawDeparts() {
        List<Ha_depart> departs = ha_departService.findAll();
        if (CollectionUtil.isNotEmpty(departs)) {
            departs = departs.stream().filter(el -> {
                // 过滤司法所的数据 1 表示司法所
                return el.getType().equals(1);
            }).collect(Collectors.toList());
        }
        return departs;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Crc_person queryById(String id) {
        Crc_person personObj = this.dao.queryById(id);
        if (ObjectUtil.isNotNull(personObj)) {
            try {
                personObj.setPhone(smService.encrypt(personObj.getPhone()));
                personObj.setName(smService.encrypt(personObj.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.queryAvatarUrl(Arrays.asList(personObj));
        return personObj;
    }


    @Value("${sfding.url: #{null}}")
    public String sfdingUrl;

    @Override
    public String sendMessage(String perid, String warnid, String workid, Integer type) {
        // 查询社矫人员
        Crc_person perObj = this.getById(perid);
        Date now = new Date();

        // 1. 司法所办案人员一条短信消息
        if (StringUtil.isEmpty(perObj.getAdid())) {
            throw new RuntimeException("社矫人员所属司法所为空 -> " + perObj.getId());
        }
        Di_userDto workPer;
        {
            ResponseDTO res = this.di_userFeign.getUserByAdid(perObj.getDeptid());
            if (res.getCode() != 0) {
                throw new RuntimeException(res.getMsg());
            }
            workPer = JSON.parseObject(JSON.toJSONString(res.getData()), Di_userDto.class);
            DidiSmsServiceImpl bean = new DidiSmsServiceImpl();
            List<String> params = new ArrayList<>();
            // 姓名
            params.add(perObj.getName());
            // 预警类型
            params.add(Tp_crc_warn.warnMap.get(String.valueOf(type)));
//            bean.sendTemplate(DidiSmsServiceImpl.tpl_crcwork_warncode, params, workPer.getMobile());
//            log.info("司法所短信发送成功 - {}", workPer.getUserName());
        }
        // 没有父级或自己本身就是父级不发后面的
        if (StringUtil.isEmpty(workPer.getFid())) {
            log.warn("社矫司法所人员父级区划id为空 -> " + workPer.getId());
            return null;
        }
        // 2. 赣政通一条待办消息, 一条短信消息
        Di_userDto lederPer;
        Di_todoDto toboObj = new Di_todoDto();
        {
            // 查询司法所的上级
            ResponseDTO res = this.di_userFeign.getUserByDeptid(workPer.getFid());
            if (res.getCode() != 0) {
                throw new RuntimeException(res.getMsg());
            }
            lederPer = JSON.parseObject(JSON.toJSONString(res.getData()), Di_userDto.class);
            if (CollectionUtil.isEmpty(lederPer.getDeptList())) {
                log.error("社矫司法所父级人员单位为空 -> " + lederPer.getId());
                throw new RuntimeException("社矫司法所父级人员单位为空 -> " + lederPer.getId());
            }
            DidiSmsServiceImpl bean = new DidiSmsServiceImpl();
            List<String> params = new ArrayList<>();
            // 姓名
            params.add(perObj.getName());
            // 预警类型
            params.add(Tp_crc_warn.warnMap.get(String.valueOf(type)));
            // 1 发送短信通知
//            bean.sendTemplate(DidiSmsServiceImpl.tpl_crcleder_warncode, params, lederPer.getMobile());
//            log.info("区县短信发送成功 - {}", lederPer.getUserName());

            // 找主部门的单位;
            Di_deptDto deptObj = null;
            for (Di_deptDto di_deptDto : lederPer.getDeptList()) {
                if (1 == di_deptDto.getIsmain()) {
                    deptObj = di_deptDto;
                    break;
                }
            }
            if (deptObj == null) {
                log.warn("{}未找到司法主部门，取消发送赣政通待办 id -> {}", lederPer.getUserName(), lederPer.getId());
                return null;
            }
            // 2 推送赣政通待办
            toboObj.setId(warnid + NanoIdUtils.randomNanoId());
            toboObj.setBt("【南昌司法】您收到了一条新的预警");
            toboObj.setWh(Tp_crc_warn.warnMap.get(String.valueOf(type)));
            toboObj.setModuleName("社区矫正");
            toboObj.setAction("社矫预警");
            toboObj.setUrgent("3");
            toboObj.setImportant("2");
            toboObj.setUrl(sfdingUrl + "?todoid=" + toboObj.getId());
            toboObj.setSendUserId(lederPer.getId());
            toboObj.setSendUserName(lederPer.getUserName());
            toboObj.setSendDeptId(deptObj.getId());
            toboObj.setSendDeptName(deptObj.getOrgname());
            toboObj.setReceiveUserId(lederPer.getId());
            toboObj.setReceiveUserName(lederPer.getUserName());
            toboObj.setReceiveDeptId(deptObj.getId());
            toboObj.setReceiveDeptName(deptObj.getOrgname());
            toboObj.setSendTime(now);
            toboObj.setPStatus(St_pStatus.PENDING);
//            this.di_todoRemoteService.afterValidateSendToDo(toboObj);
            log.info("区县待办保存成功 - {}", JSON.toJSONString(toboObj));
        }
        // 3. 保存一条系统收到记录
        Cre_work_record recordObj = new Cre_work_record();
        recordObj.setId(workid + NanoIdUtils.randomNanoId());
        recordObj.setExectime(now);
        recordObj.setWorkid(workid);
        recordObj.setRecord("发现预警，派发任务。（系统自动派发任务）");
        this.cre_work_recordService.saveOrUpdate(recordObj);
//        return toboObj.getId();
        return null;
    }

    public void sendSupMessage(String warnid, String workid) {
        Cre_warning warnObj = this.cre_warningService.getById(warnid);
        // 查询社矫人员
        Crc_person perObj = this.getById(warnObj.getPerid());
        // 1. 司法所办案人员一条短信消息
        if (StringUtil.isEmpty(perObj.getAdid())) {
            throw new RuntimeException("社矫人员所属司法所为空 -> " + perObj.getId());
        }
        Di_userDto workPer;
        {
            ResponseDTO res = this.di_userFeign.getUserByAdid(perObj.getDeptid());
            if (res.getCode() != 0) {
                throw new RuntimeException(res.getMsg());
            }
            workPer = JSON.parseObject(JSON.toJSONString(res.getData()), Di_userDto.class);
            DidiSmsServiceImpl bean = new DidiSmsServiceImpl();
            List<String> params = new ArrayList<>();
            // 姓名
            params.add(perObj.getName());
            // 预警类型
            params.add(Tp_crc_warn.warnMap.get(String.valueOf(warnObj.getType())));
//            bean.sendTemplate(DidiSmsServiceImpl.tpl_crcwork_supcode, params, workPer.getMobile());
//            log.info("司法所短信发送成功 - {}", workPer.getUserName());
        }
        // 2. 赣政通一条待办消息, 一条短信消息
        if (StringUtil.isEmpty(workPer.getFid())) {
            log.warn("社矫司法所人员父级区划id为空-> " + workPer.getId());
            return;
        }
        Di_userDto lederPer;
        Date now = new Date();
        {
            // 查询司法所的上级
            ResponseDTO res = this.di_userFeign.getUserByDeptid(workPer.getFid());
            if (res.getCode() != 0) {
                throw new RuntimeException(res.getMsg());
            }
            lederPer = JSON.parseObject(JSON.toJSONString(res.getData()), Di_userDto.class);
            if (CollectionUtil.isEmpty(lederPer.getDeptList())) {
                log.error("社矫司法所父级人员单位为空");
                throw new RuntimeException("社矫司法所父级人员单位为空");
            }
            DidiSmsServiceImpl bean = new DidiSmsServiceImpl();
            List<String> params = new ArrayList<>();
            // 姓名
            params.add(perObj.getName());
            // 预警类型
            params.add(Tp_crc_warn.warnMap.get(String.valueOf(warnObj.getType())));
            // 1 发送短信通知
//            bean.sendTemplate(DidiSmsServiceImpl.tpl_crcleder_supcode, params, lederPer.getMobile());
//            log.info("区县短信发送成功 - {}", lederPer.getUserName());

            // 2 推送赣政通消息
            Di_messageDto messageObj = new Di_messageDto();
            messageObj.setId(warnid + NanoIdUtils.randomNanoId());
            messageObj.setSendUserId(lederPer.getId());
            messageObj.setSendUserName(lederPer.getUserName());
            messageObj.setReceiveUserId(lederPer.getId());
            messageObj.setReceiveUserName(lederPer.getUserName());
            messageObj.setContent("收到一条督办通知，你辖区内社区矫正对象【" + perObj.getName() + "】，触发【" + Tp_crc_warn.warnMap.get(String.valueOf(warnObj.getType())) + "】预警，请尽快安排工作人员处理，并将结果上传系统");
            messageObj.setActUrl(sfdingUrl + "?msgid=" + messageObj.getId());
            messageObj.setRemindType(3);
            messageObj.setSendTime(now);
//            this.di_todoRemoteService.afterValidateSendMessage(messageObj);

        }
    }

    @Override
    public List<Crc_person> getList() {
        List<Crc_person> personList = this.dao.getList();
        for (Crc_person personInfo : personList) {
            try {
                personInfo.setPhone(smService.encrypt(personInfo.getPhone()));
                personInfo.setName(smService.encrypt(personInfo.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return personList;
    }

    @Override
    public List<Crc_departBO> findDepartByPerson(String personId) {
        Crc_person person = this.getById(personId);
        if (ObjectUtil.isNotNull(person)) {
            List<Map<String, Object>> departList = this.dao.findDepartByAdid(person.getAdid());
            if (CollUtil.isNotEmpty(departList)) {
                return BeanUtil.copyToList(departList, Crc_departBO.class);
            }
        }
        return Collections.emptyList();
    }

    @Override
    public List<Crc_person> findAllFocus(List<String> f_deptid) {
        List<Crc_person> personList = dao.findByDeptID(f_deptid);
        if (CollUtil.isEmpty(personList)) {
            return null;
        }
        List<Crc_person> result = new ArrayList<>();
        for (Crc_person person : personList) {
            if (person.getFocus() != YesNo.YES) {
                continue;
            }
            try {
                person.setPhone(smService.encrypt(person.getPhone()));
                person.setName(smService.encrypt(person.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.add(person);
        }
        List<Crc_person> filteredList = personList.stream()
                .filter(p -> p.getFocus() == YesNo.YES)
                .collect(Collectors.toList());
        return filteredList;
    }

    @Override
    public List<Crc_departBO> findDepartByPersons(List<String> personIds) {
        List<Crc_person> personList = dao.findByPersonIds(personIds);
        if (CollUtil.isNotEmpty(personList)) {
            List<String> adids = personList.stream().filter(el -> ObjectUtil.isNotNull(el.getDeptid()))
                    .map(Crc_person::getDeptid).distinct().collect(Collectors.toList());
            List<Map<String, Object>> departList = this.dao.findDepartByAdids(adids);
            if (CollUtil.isNotEmpty(departList)) {
                List<Crc_departBO> departBoList = BeanUtil.copyToList(departList, Crc_departBO.class);
                List<String> parentIds = departBoList.stream().filter(el -> ObjectUtil.isNotNull(el.getFid()))
                        .map(Crc_departBO::getFid).distinct().collect(Collectors.toList());
                List<Map<String, Object>> parentDepartList = this.dao.findDepartByParentIds(parentIds);
                if (CollUtil.isNotEmpty(parentDepartList)) {
                    departBoList.addAll(BeanUtil.copyToList(parentDepartList, Crc_departBO.class));
                }
                return departBoList;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public List<Crc_person> queryListByIsFocus(Integer isFocus) {
        return this.dao.queryListByIsFocus(isFocus);
    }


}
